package com.langchain4j.core.example;

import com.langchain4j.core.llm.factory.LLMProviderFactory;
import com.langchain4j.core.llm.model.GenerationConfig;
import com.langchain4j.core.llm.provider.LLMProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * LLM使用示例
 */
@Slf4j
@Component
public class LLMExample implements CommandLineRunner {
    
    @Autowired
    private LLMProviderFactory providerFactory;
    
    @Override
    public void run(String... args) throws Exception {
        log.info("开始LLM示例测试");
        
        // 测试OpenAI
        testOpenAI();
        
        // 测试百度文心一言
        testBaidu();
        
        log.info("LLM示例测试完成");
    }
    
    /**
     * 测试OpenAI
     */
    private void testOpenAI() {
        try {
            log.info("=== 测试OpenAI ===");
            
            LLMProvider provider = providerFactory.getProvider("openai");
            
            // 测试文本生成
            GenerationConfig config = GenerationConfig.builder()
                    .temperature(0.7)
                    .maxTokens(100)
                    .build();
            
            var result = provider.generate("请介绍一下Java编程语言", config).get();
            
            if (result.getSuccess()) {
                log.info("OpenAI生成结果: {}", result.getContent());
                log.info("Token使用: {}", result.getTokenUsage());
            } else {
                log.error("OpenAI调用失败: {}", result.getErrorMessage());
            }
            
        } catch (Exception e) {
            log.error("OpenAI测试失败", e);
        }
    }
    
    /**
     * 测试百度文心一言
     */
    private void testBaidu() {
        try {
            log.info("=== 测试百度文心一言 ===");
            
            LLMProvider provider = providerFactory.getProvider("baidu");
            
            // 测试文本生成
            GenerationConfig config = GenerationConfig.builder()
                    .temperature(0.7)
                    .maxTokens(100)
                    .build();
            
            var result = provider.generate("请介绍一下人工智能", config).get();
            
            if (result.getSuccess()) {
                log.info("百度生成结果: {}", result.getContent());
                log.info("Token使用: {}", result.getTokenUsage());
            } else {
                log.error("百度调用失败: {}", result.getErrorMessage());
            }
            
        } catch (Exception e) {
            log.error("百度测试失败", e);
        }
    }
} 